import path from 'path'
import fs from 'fs'
import replace from 'rollup-plugin-replace'
import alias from 'rollup-plugin-alias'
import json from 'rollup-plugin-json'
import ts from 'rollup-plugin-typescript2'
import {
  terser
} from 'rollup-plugin-terser'

const packagesDir = path.resolve(__dirname, 'packages')
const packageDir = path.resolve(packagesDir, process.env.TARGET)
const name = path.basename(packageDir) // process.env.TARGET
const resolve = p => path.resolve(packageDir, p)

// et aliasOptions = { resolve: ['.ts'], entries: {} }
let aliasOptions = {
  resolve: ['.ts']
}
fs.readdirSync(packagesDir).forEach(dir => {
  if (fs.statSync(path.resolve(packagesDir, dir)).isDirectory()) {
    aliasOptions[`@wahaha/${dir}`] = path.resolve(packagesDir, `${dir}/src/index`)
  }
})

// const moduleStrLength = name.slice('module'.length) + 1
// const moduleNumner = name.slice(moduleStrLength)
// const ABC = ['one', 'two', 'three']
// console.log(moduleStrLength,
//   moduleNumner)
// name = ABC[moduleNumner]



let aliasPlugin = alias(aliasOptions)

let optionConfig = []
const configs = {
  es: {
    file: resolve(`dist/${name}.es.js`),
    format: 'es'
  },
  cjs: {
    file: resolve(`dist/${name}.cjs.js`),
    format: 'cjs'
  },
  global: {
    file: resolve(`dist/${name}.global.js`),
    format: 'iife',
    name: name.split('-').join('')
  },
  'es-brower': {
    file: resolve(`dist/${name}.es-brower.js`),
    format: 'es'
  }
}

;
(() => {
  for (const format of Object.keys(configs)) {
    optionConfig.push(createdOptionCreated(format))
  }
})()

function createdOptionCreated(format) {
  let output = configs[format]
  let isGrobalBuild = output.format === 'iife'
  let isBrowserESMBuild = format === 'es-brower'
  return {
    input: resolve('src/index.ts'),
    output,
    external: isGrobalBuild || isBrowserESMBuild ? [] : ['resolve', 'wahaha-one', '@wahaha-two', '@wahaha-three'],
    plugins: [
      json(),
      ts({
        check: false,
        tsconfig: path.resolve(__dirname, 'tsconfig.json'),
        cacheRoot: path.resolve(__dirname, 'node_modules/.rts2_cache')
      }),
      aliasPlugin,
      replace({
        __TEST__: process.env.__TEST__
      }),
      isGrobalBuild || isBrowserESMBuild ?
      terser({
        output: {
          comments: function (node, comment) {
            var text = comment.value
            var type = comment.type // 注释类型
            console.log(text, type)
            // if (type == 'comment2') {
            //   // multiline comment
            return /@preserve|@license|@cc_on|console/i.test(text)
            // }
          }
        }
      }) :
      ''
    ]
  }
}
export default optionConfig